package interfaz;

import clases.ClsDatabase;
import clases.ClsException;
import clases.ClsMetodos;
import clases.renderIcono;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author SER
 */
public class dlgAportes_2 extends javax.swing.JDialog {

    private ClsMetodos metodos = new ClsMetodos();
    private ClsDatabase bd = new ClsDatabase();
    DefaultComboBoxModel modelCboTipoInsumo = new DefaultComboBoxModel();
    DefaultComboBoxModel modelCboIndice = new DefaultComboBoxModel();
    DefaultComboBoxModel modelCboInstitucion = new DefaultComboBoxModel();
    DefaultComboBoxModel modelnombre = new DefaultComboBoxModel();
    JComboBox cbgrupo1 = new JComboBox();
    String id_proyecto = "1";
    boolean existe = true;
//    String idString=null;
    /**
     * Creates new form dlgInsumos2
     *
     * @param parent
     * @param modal
     */
    int c1, c2;

    public dlgAportes_2(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        _iniciar();//Iniciamos algunos componentes por defecto...

    }

    public dlgAportes_2(java.awt.Dialog parent, boolean modal, String id) {
        super(parent, modal);
        initComponents();

        id_proyecto = id;
        _iniciar();//Iniciamos algunos componentes por defecto...
    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public final void _iniciar() {
        setLocationRelativeTo(null);
//        metodos._iconJDialog(this);
        alinear_tabla();
        txtBuscar.setText("");
        txtBuscar.requestFocus();
        existencia();
        c1 = 0;
        c2 = 0;
        metodos.comboboxLlenarMas(cboTipoInsumo, modelCboTipoInsumo, "SELECT idinsumo_tipo,nombre FROM insumo_tipo");
//        metodos.comboboxLlenarMas(cboIndice, modelCboIndice, "SELECT idinsumo_indice,concat(idinsumo_indice,'-',descripcion) FROM insumo_indice");
        seleccionar_cargas();

        c1 = 1;
        c2 = 1;
        tblInsumos.setDefaultRenderer(Object.class, new renderIcono());
        metodos.tablaLongitudColumnas(tblInsumos, new int[]{0, 20, 20, 250, 40, 80, 80, 0, 15, 80, 15, 80, 15, 80, 50});
        metodos.tablaOcultarcolumnas(tblInsumos, new int[]{0, 7});
        combo_grupo();
        // tblInsumos.getColumnModel().getColumn(6).setCellEditor(new clases.ClsCellEditorInsumoPrecio(bd, 1, this));
    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public void combo_grupo() {
        TableColumn sportColumn1 = tblInsumos.getColumnModel().getColumn(9);
        TableColumn sportColumn2 = tblInsumos.getColumnModel().getColumn(11);
        TableColumn sportColumn3 = tblInsumos.getColumnModel().getColumn(13);
        cbgrupo1.removeAllItems();
        comboboxLlenar(cbgrupo1, modelCboInstitucion, modelnombre, "SELECT idinstitucion,nombre FROM institucion");

        //        cbgrupo1.addItem("Gobierno local");
//        cbgrupo1.addItem("Agua Limpia");
        sportColumn1.setCellEditor(new DefaultCellEditor(cbgrupo1));
        sportColumn2.setCellEditor(new DefaultCellEditor(cbgrupo1));
        sportColumn3.setCellEditor(new DefaultCellEditor(cbgrupo1));
    }

    public void comboboxLlenar(JComboBox cb, DefaultComboBoxModel model, DefaultComboBoxModel modelnombre, String sql) {
        model.removeAllElements();
        cb.removeAllItems();
        try {
            bd.getConnection();
            PreparedStatement pstm = bd.conn.prepareStatement(sql);
            System.out.println("combobox--> " + sql);
            ResultSet res = pstm.executeQuery();
            while (res.next()) {
                model.addElement(res.getString(1));
                String nombre = res.getString(2);
                modelnombre.addElement(nombre);
                cb.addItem(nombre);
            }
            res.close();
        } catch (Exception e) {
            System.err.println(e);
            ClsException._exceptionWriteFile(e, "comboboxLlenar");
        }
        cb.setSelectedIndex(-1);
        cb.setPopupVisible(false);
    }

    public void marcar_nuevo() {
        int n = tblInsumos.getRowCount();
        for (int i = 0; i < n; i++) {
            String val = "Gobierno Local";
            tblInsumos.setValueAt(val, i, 9);
            tblInsumos.setValueAt("100", i, 8);
            val = "Sin convenio";
            tblInsumos.setValueAt(val, i, 11);
            tblInsumos.setValueAt("0", i, 10);
            val = "Sin convenio";
            tblInsumos.setValueAt(val, i, 13);
            tblInsumos.setValueAt("0", i, 12);
            tblInsumos.setValueAt("100", i, 14);
        }
    }

    public void marcar_tipo_insumo() {
        int n = tblInsumos.getRowCount();
        String cod = modelCboTipoInsumo.getElementAt(cboTipoInsumo.getSelectedIndex()).toString();
        for (int i = 0; i < n; i++) {

            if (tblInsumos.getValueAt(i, 7).toString().equals(cod)) {
                tblInsumos.changeSelection(i, 1, false, false);
                break;
            }

        }
    }

    public void marcar_nombre() {
        int n = tblInsumos.getRowCount();
        String buscado = txtBuscar.getText();
        int l = buscado.length();
        boolean para = false;
        for (int i = 0; i < n; i++) {
            String base = tblInsumos.getValueAt(i, 3).toString();
            if (base.length() >= l) {
                for (int j = 0; j < base.length() - l; j++) {
                    String recorte = base.substring(j, l + j);
                    //System.out.println(recorte);
                    if (recorte.equalsIgnoreCase(buscado)) {
                        tblInsumos.changeSelection(i, 1, false, false);
                        para = true;
                        break;
                    }
                }
            }
            if (para == true) {
                break;
            }
        }
        if (para == false) {
            //tblInsumos.changeSelection(-1, 1, false, false);
            //tblInsumos.getSelectionModel().setSelectionInterval(-1, -1);
        }
    }

    public void marcar_nombreddd() {
        int n = tblInsumos.getRowCount();
        String buscado = txtBuscar.getText();
        int l = buscado.length();
        for (int i = 0; i < n; i++) {
            String base = tblInsumos.getValueAt(i, 3).toString();
            if (base.length() >= l) {
                if (base.substring(0, l).equalsIgnoreCase(buscado)) {
                    tblInsumos.changeSelection(i, 1, false, false);
                    break;
                }
            }
        }
    }

    public void alinear_tabla() {
        //izquierda
        DefaultTableCellRenderer modelocentrar = new DefaultTableCellRenderer();
        modelocentrar.setHorizontalAlignment(SwingConstants.RIGHT);
        tblInsumos.getColumnModel().getColumn(5).setCellRenderer(modelocentrar);
        tblInsumos.getColumnModel().getColumn(6).setCellRenderer(modelocentrar);
        tblInsumos.getColumnModel().getColumn(7).setCellRenderer(modelocentrar);
    }

    public void seleccionar_base(String valor) {
        metodos.seleccionar_tabla(tblInsumos, 0, valor);
    }

    public void existencia() {
        existe = true;
        existe = bd.verif_repite("SELECT idproyecto FROM contrapartida WHERE idproyecto='" + id_proyecto + "'");
    }

    public void seleccionar_cargas() {
        if (!existe) {
            _cargarDatosTablell();
            marcar_nuevo();
        } else {
            _cargarDatosTable_guardado();
        }
    }

    public void _cargarDatosTablell() {
        String nombreBuscar = txtBuscar.getText().toString();//,sum(partida_detalle.`precio_parcial`)
        String sql = "", sql2 = "";
        //insumo_tipo.`abreviatura`
        sql = " insumo.`idinsumo`,'',insumo_tipo.`idinsumo_tipo` ,insumo.`nombre` ,unidad.`simbolo`,"
                + "sum(partida_detalle.`cantidad`) ,insumo.`precio`,insumo_tipo.`idinsumo_tipo` "
                + ",'','','','','','',''";
        sql2 = "FROM "
                + "     `partida_detalle` partida_detalle INNER JOIN `insumo` insumo ON partida_detalle.`idinsumo` = insumo.`idinsumo`\n"
                + "     INNER JOIN `unidad` unidad ON insumo.`idunidad` = unidad.`idunidad`\n"
                + "     INNER JOIN `insumo_tipo` insumo_tipo ON insumo.`idinsumo_tipo` = insumo_tipo.`idinsumo_tipo`\n"
                + "     INNER JOIN `insumo_indice` insumo_indice ON insumo.`idinsumo_indice` = insumo_indice.`idinsumo_indice`\n"
                + "WHERE\n"
                + "     partida_detalle.idproyecto = '" + id_proyecto + "'    "
                + "  "
                + "GROUP BY insumo.`idinsumo`,insumo.`nombre` ,	unidad.`simbolo`,"
                + "insumo.`precio` ,"
                + " insumo_indice.`descripcion`,insumo_tipo.`idinsumo_tipo`"
                + "ORDER BY\n"
                + "     insumo_tipo.`orden` ASC,\n"
                + "     insumo.`nombre` ASC";
        tablaLlenaSql_defecto(tblInsumos, sql, sql2);
        metodos.tablaRedondea(tblInsumos, new int[]{5, 6});
        metodos.tablaNumeracion(tblInsumos, new int[]{1});
        iconos_tipo_insumo(tblInsumos, 7, 2);
        //quitar_eyh(tblInsumos);
    }
    

    public void _cargarDatosTable_guardado() {
        String nombreBuscar = txtBuscar.getText().toString();//,sum(partida_detalle.`precio_parcial`)
        String sql = "", sql2 = "";
        //insumo_tipo.`abreviatura`
        sql = "      contrapartida.`idinsumo` , '',insumo.`idinsumo_tipo`  ,insumo.`nombre` ,unidad.`simbolo` ,\n" +
"     contrapartida.`cantidad`,insumo.`precio` ,insumo.`idinsumo_tipo` ,contrapartida.`porcentaje1`,\n" +
"     institucion.`nombre` ,contrapartida.`porcentaje2` ,institucion_A.`nombre` ,contrapartida.`porcentaje3`,\n" +
"     institucion_B.`nombre` ,contrapartida.`total`";
        sql2 = "FROM\n" +
"     `insumo` insumo INNER JOIN `contrapartida` contrapartida ON insumo.`idinsumo` = contrapartida.`idinsumo`\n" +
"     INNER JOIN `unidad` unidad ON insumo.`idunidad` = unidad.`idunidad`\n" +
"     INNER JOIN `insumo_tipo` insumo_tipo ON insumo.`idinsumo_tipo` = insumo_tipo.`idinsumo_tipo`\n" +
"     INNER JOIN `institucion` institucion ON contrapartida.`idinstitucion1` = institucion.`idinstitucion`\n" +
"     INNER JOIN `institucion` institucion_A ON contrapartida.`idinstitucion2` = institucion_A.`idinstitucion`\n" +
"     INNER JOIN `institucion` institucion_B ON contrapartida.`idinstitucion3` = institucion_B.`idinstitucion`\n" +
"     INNER JOIN `proyecto` proyecto ON contrapartida.`idproyecto` = proyecto.`idproyecto`\n" +
"WHERE\n" +
"     contrapartida.idproyecto = '" + id_proyecto + "'\n" +
"ORDER BY\n" +
"     insumo_tipo.`orden` ASC,insumo.`nombre` ASC";
        tablaLlenaSql_defecto(tblInsumos, sql, sql2);
        metodos.tablaRedondea(tblInsumos, new int[]{5, 6});
        metodos.tablaNumeracion(tblInsumos, new int[]{1});
        iconos_tipo_insumo(tblInsumos, 7, 2);
        //quitar_eyh(tblInsumos);
    }

    public boolean tablaLlenaSql_defecto(javax.swing.JTable table, String camposSelect, String sqlFromWhere) {
        DefaultTableModel mdt = (DefaultTableModel) table.getModel();
        metodos.tablaLimpia(mdt);
        boolean va = true;
        String sql = "SELECT " + camposSelect + " " + sqlFromWhere;
        int n = 0;
        try {
            bd.getConnection();
            PreparedStatement pstm = bd.conn.prepareStatement(sql);
            ResultSet res = pstm.executeQuery();

            //Previene que en camposSelect tenga: * o concat(   -->para obtener el numero de columnas
//            if (camposSelect.trim().equals("*") || camposSelect.toLowerCase().indexOf("concat(") != -1) {
            ResultSetMetaData rsmd = res.getMetaData();
            n = rsmd.getColumnCount();
//            } else {
//                String colname[] = camposSelect.split(",");
//                n = colname.length;
//            }
//            System.err.println("n-Result-getColumnCount: "+String.valueOf(n));

            while (res.next()) {

                Object mat[] = new Object[n];
                for (int i = 0; i < n; i++) {
                    mat[i] = res.getString(i + 1);
                }
                if (mat[4].toString().equals("%mo") == false) {
                    mdt.addRow(mat);
                }

            }
            res.close();
        } catch (Exception e) {
            System.err.println("sql: " + e);
            e.printStackTrace();
            ClsException._exceptionWriteFile(e, "tablaLlenaSql");
        }

        //System.out.println("tablaLlenaSql--> " + sql);
        return va;
    }

    public void grabar() {
        DefaultTableModel mdt = (DefaultTableModel) tblInsumos.getModel();
        int n = mdt.getRowCount();
        bd.delete("contrapartida", "idproyecto='" + id_proyecto + "'");
        for (int i = 0; i < n; i++) {
            String inst1 = modelCboInstitucion.getElementAt(modelnombre.getIndexOf(mdt.getValueAt(i, 9))).toString();
            String inst2 = modelCboInstitucion.getElementAt(modelnombre.getIndexOf(mdt.getValueAt(i, 11))).toString();
            String inst3 = modelCboInstitucion.getElementAt(modelnombre.getIndexOf(mdt.getValueAt(i, 13))).toString();
            bd.insert("contrapartida", "idproyecto, idinsumo,cantidad, porcentaje1, idinstitucion1, porcentaje2, idinstitucion2, porcentaje3, idinstitucion3, total", "'" + id_proyecto + "','" + mdt.getValueAt(i, 0) + "','"+ mdt.getValueAt(i, 5)+"','" + mdt.getValueAt(i, 8) + "','" + inst1 + "','" + mdt.getValueAt(i, 10) + "','" + inst2 + "','" + mdt.getValueAt(i, 12) + "','" + inst3 + "','" + mdt.getValueAt(i, 14) + "'");
        }
    }

    public void calculo_parcial(Object valor) {
        int fila = tblInsumos.getSelectedRow();
        if (fila != -1) {
            double cant = Double.parseDouble(tblInsumos.getValueAt(fila, 5).toString());
            double pre = Double.parseDouble(valor.toString());
            double tot = cant * pre;
            tblInsumos.setValueAt(metodos.redondeo_2(tot), fila, 7);
        }

    }

    public void iconos_tipo_insumo(javax.swing.JTable tabla, int col_tipo, int col_asigna) {
        ImageIcon icon1 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_material_16.png"));
        ImageIcon icon2 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_obrero.png"));
        ImageIcon icon3 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_herramienta_12.png"));
        ImageIcon icon4 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_servicios.png"));
        int n = tabla.getRowCount();
        for (int i = 0; i < n; i++) {
            String valor = tabla.getValueAt(i, col_tipo).toString();
            if (valor.equals("1")) {
                tabla.setValueAt(new JLabel(icon1), i, col_asigna);
            } else if (valor.equals("2")) {
                tabla.setValueAt(new JLabel(icon2), i, col_asigna);
            } else if (valor.equals("3")) {
                tabla.setValueAt(new JLabel(icon3), i, col_asigna);
            } else if (valor.equals("4")) {
                tabla.setValueAt(new JLabel(icon4), i, col_asigna);
            } else {
                tabla.setValueAt(new JLabel(icon3), i, col_asigna);
            }
        }
    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public void EliminarInsumo() {
        int fila = tblInsumos.getSelectedRow();//Obtenemos la fila seleccionada
        if (fila != -1) {
            //Confirmamos la eliminacion
            if (JOptionPane.showConfirmDialog(null, "Está seguro que desea eliminar el Insumo seleccionado", "Mensaje", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                String id = tblInsumos.getValueAt(fila, 0).toString();
                boolean seRepite = bd.verif_repite("SELECT idinsumo FROM partida_detalle WHERE idinsumo='" + id + "'");
                if (!seRepite) {
                    seRepite = bd.verif_repite("SELECT idinsumo FROM partida_base_detalle WHERE idinsumo='" + id + "'");
                    if (!seRepite) {
                        boolean seElimino = bd.delete("insumo", "idinsumo='" + id + "'");
                        if (seElimino) {
                            seleccionar_cargas();
                            //JOptionPane.showMessageDialog(null, "Se elimino el Insumo con exito");
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "No se puede eliminar este Insumo porque ya está siendo utilizado");
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "Seleccione un Insumo");
        }
    }

    public void reporte(int opcion) {
        if (opcion == 1) {
            metodos.reporte_estandar("contrapartidas.jasper", new String[]{id_proyecto, ""}, "Reporte Sub Presupuesto", 1080, 650);
        } else if (opcion == 2) {
            //metodos.reporte_estandar("acu_sub.jasper", new String[]{codigo_proyecto, idpresupuesto}, "Reporte Análisis de costos unitarios", 1080, 650);
        }
    }
//___________________________________________________________________________________ Soy una barra separadora :)

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlInsumos = new javax.swing.JPanel();
        pnlTablaInsumo = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblInsumos = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtBuscar = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        cboTipoInsumo = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jToolBar2 = new javax.swing.JToolBar();
        btnNuevoCategoria1 = new javax.swing.JButton();
        btnVer = new javax.swing.JButton();
        btnEliminarCategoria = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Contrapartida del Proyecto: ");
        setResizable(false);

        pnlTablaInsumo.setBackground(new java.awt.Color(225, 235, 247));
        pnlTablaInsumo.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tblInsumos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Cód.", "N°", "", "Descripción", "Unidad", "Cantidad", "P. Unitario", "tipo", "%", "Aporte 1", "%", "Aporte 2", "%", "Aporte 3", "Total"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, true, true, true, true, true, true, true, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblInsumos.setRowHeight(23);
        tblInsumos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblInsumos.getTableHeader().setReorderingAllowed(false);
        tblInsumos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblInsumosMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(tblInsumos);

        pnlTablaInsumo.add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 135, 1070, 200));

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/salir.png"))); // NOI18N
        jButton1.setText("Salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(980, 510, 102, -1));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Buscar"));
        jPanel1.setOpaque(false);
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscarKeyReleased(evt);
            }
        });
        jPanel1.add(txtBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(67, 27, 270, -1));

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Nombre:");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 27, -1, 25));

        cboTipoInsumo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboTipoInsumo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboTipoInsumoActionPerformed(evt);
            }
        });
        jPanel1.add(cboTipoInsumo, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 27, 170, -1));

        jLabel9.setText("Tipo insumo:");
        jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(355, 30, -1, -1));

        pnlTablaInsumo.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 50, 1070, 70));

        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);
        jToolBar2.setOpaque(false);

        btnNuevoCategoria1.setForeground(new java.awt.Color(3, 90, 180));
        btnNuevoCategoria1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/editar.png"))); // NOI18N
        btnNuevoCategoria1.setText("Editar Institución");
        btnNuevoCategoria1.setFocusable(false);
        btnNuevoCategoria1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnNuevoCategoria1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoCategoria1ActionPerformed(evt);
            }
        });
        jToolBar2.add(btnNuevoCategoria1);

        btnVer.setForeground(new java.awt.Color(3, 90, 180));
        btnVer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/ver_reporte.png"))); // NOI18N
        btnVer.setText("Reportes");
        btnVer.setFocusable(false);
        btnVer.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnVer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btnVerMousePressed(evt);
            }
        });
        btnVer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVerActionPerformed(evt);
            }
        });
        jToolBar2.add(btnVer);

        btnEliminarCategoria.setForeground(new java.awt.Color(3, 90, 180));
        btnEliminarCategoria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/guardar.png"))); // NOI18N
        btnEliminarCategoria.setText("Guardar");
        btnEliminarCategoria.setFocusable(false);
        btnEliminarCategoria.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEliminarCategoria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarCategoriaActionPerformed(evt);
            }
        });
        jToolBar2.add(btnEliminarCategoria);

        pnlTablaInsumo.add(jToolBar2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1090, -1));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        pnlTablaInsumo.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 330));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Resumen"));
        jPanel2.setOpaque(false);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Rubro", "Gobierno local", "Agua Limpia", "Jass", "% Aporte"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(26, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 27, Short.MAX_VALUE))
        );

        pnlTablaInsumo.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 350, 500, 200));

        javax.swing.GroupLayout pnlInsumosLayout = new javax.swing.GroupLayout(pnlInsumos);
        pnlInsumos.setLayout(pnlInsumosLayout);
        pnlInsumosLayout.setHorizontalGroup(
            pnlInsumosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlTablaInsumo, javax.swing.GroupLayout.DEFAULT_SIZE, 1093, Short.MAX_VALUE)
        );
        pnlInsumosLayout.setVerticalGroup(
            pnlInsumosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlTablaInsumo, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlInsumos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlInsumos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblInsumosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblInsumosMouseClicked
    }//GEN-LAST:event_tblInsumosMouseClicked

    private void txtBuscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyReleased
        marcar_nombre();
    }//GEN-LAST:event_txtBuscarKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cboTipoInsumoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboTipoInsumoActionPerformed
        if (c1 == 1) {
            marcar_tipo_insumo();
        }
    }//GEN-LAST:event_cboTipoInsumoActionPerformed

    private void btnNuevoCategoria1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoCategoria1ActionPerformed
        dlgInstitucion dialog = new dlgInstitucion(this, true);
        dialog.setVisible(true);
    }//GEN-LAST:event_btnNuevoCategoria1ActionPerformed

    private void btnEliminarCategoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarCategoriaActionPerformed
        grabar();
    }//GEN-LAST:event_btnEliminarCategoriaActionPerformed

    private void btnVerMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnVerMousePressed
//        menuPresupuesto.show(evt.getComponent(), 0, 30);
    }//GEN-LAST:event_btnVerMousePressed

    private void btnVerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerActionPerformed
        reporte(1);
    }//GEN-LAST:event_btnVerActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgAportes_2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgAportes_2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgAportes_2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgAportes_2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlgAportes_2 dialog = new dlgAportes_2(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEliminarCategoria;
    private javax.swing.JButton btnNuevoCategoria1;
    private javax.swing.JButton btnVer;
    private javax.swing.JComboBox cboTipoInsumo;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JToolBar jToolBar2;
    public javax.swing.JPanel pnlInsumos;
    private javax.swing.JPanel pnlTablaInsumo;
    private javax.swing.JTable tblInsumos;
    private javax.swing.JTextField txtBuscar;
    // End of variables declaration//GEN-END:variables
}
